package com.ionehe.group.common.file.ex.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;

/**
 * 数据源配置
 * @author 2022/1/14 <a href="mailto:a@ionehe.com">xiu</a>
 */
@Configuration
@PropertySource({"classpath:f_db.properties"})
@MapperScan(basePackages = FileExDataSourceConfiguration.PACKAGE, sqlSessionFactoryRef = "fileSqlSessionFactory")
public class FileExDataSourceConfiguration {
    /**
     * 精确到 目录，以便跟其他数据源隔离
     */
    static final String PACKAGE = "com.ionehe.group.common.file.ex.repository.dao";
    static final String MAPPER_LOCATION = "classpath*:com/ionehe/group/common/file/ex/repository/dao/*.xml";

    @Bean(name = "fileExTransactionManager")
    //@Primary
    public DataSourceTransactionManager fileExTransactionManager() {
        return new DataSourceTransactionManager(fileExDataSource());
    }

    @Bean(name = "fileSqlSessionFactory")
    //@Primary
    public SqlSessionFactory fileSqlSessionFactory(@Qualifier("fileExDataSource") DataSource fileExDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(fileExDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(FileExDataSourceConfiguration.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }

    @Value("${file.ex.druid.type}")
    private Class<? extends DataSource> dataSourceType;

    @Bean(name = "fileExDataSource")
    @ConfigurationProperties(prefix = "file.ex.druid.jdbc")
    //@Primary
    public DataSource fileExDataSource(){
        return DataSourceBuilder.create().type(dataSourceType).build();
    }
}